<template>
  <div class="comment-post">
    <van-field
      class="post-field"
      v-model.trim="message"
      rows="2"
      autosize
      type="textarea"
      maxlength="50"
      placeholder="请输入留言"
      show-word-limit
    />
    <van-button
      @click="onPost"
      class="post-btn"
    >发布</van-button>
  </div>
</template>

<script>
import { addComment } from '@/api/comment'
export default {
  // 依赖注入
  inject: ['articleId'],
  name: 'CommentPost',
  props: {
    target: {
      type: [String, Number, Object],
      required: true
    },
    type: {
      type: String,
      default: 'a',
      validator(val) {
        return ['a', 'c'].includes(val)
      }
    }
  },
  data () {
    return {
      message: ''
    }
  },
  computed: {},
  watch: {},
  created () {},
  mounted () {},
  methods: {
    async onPost() {
      this.$toast.loading({
        message: '发布中...',
        forbidClick: true,
        duration: 0 // 持续展示 toast
      })
      if (this.message.trim() !== '') {
        try {
          const { data } = await addComment({
            target: this.target,
            content: this.message,
            art_id: this.type === 'c' ? this.articleId : null
          })
          //   console.log(data);
          this.message = ''
          //   子传父
          this.$emit('postSuccess', data.data.new_obj)
          this.$toast.success('发布成功！')
        } catch (error) {
          this.$toast.fail('发布评论失败！')
        }
      } else {
        this.$toast('评论内容不能为空！')
      }
    }
  }
}
</script>

<style scoped lang="less">
.comment-post {
  display: flex;
  align-items: center;
  padding: 32px 0 32px 32px;
  .post-field {
    background-color: #f5f7f9;
  }
  .post-btn {
    width: 150px;
    border: none;
    padding: 0;
    color: #6ba3d8;
    &::before {
      display: none;
    }
  }
}
</style>
